package servlet;

import anno.Autowired;
import anno.RequestBody;
import anno.ResponseBody;
import dao.AttendanceRecordDAO;
import pojo.AttendanceRecord;
import utils.ApiResult;
import utils.JDBCUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/attendanceRecord")
public class AttendanceRecordServlet extends BaseServlet {

    @Autowired
    private AttendanceRecordDAO attendanceRecordDAO;
    /**
     * 更新考勤记录
     *
     * @param req       HttpServletRequest
     * @param resp      HttpServletResponse
     * @param record    考勤记录对象
     * @return 更新结果
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult update(HttpServletRequest req, HttpServletResponse resp, @RequestBody AttendanceRecord record) throws SQLException {
        boolean success = attendanceRecordDAO.update(record);
        if (success) {
            return new ApiResult(200, "更新考勤记录成功", null);
        } else {
            return new ApiResult(500, "更新考勤记录失败", null);
        }
    }
    /**
     * 分页模糊查询考勤记录
     *
     * @param req       HttpServletRequest
     * @param resp      HttpServletResponse
     * @param keyword   模糊查询关键字
     * @param pageNum   当前页码
     * @param pageSize  每页记录数
     * @return 分页查询结果
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult findRecordsByPageAndKeyword(HttpServletRequest req, HttpServletResponse resp, String keyword, String pageNum, String pageSize) throws SQLException {
        int pageNumInt = Integer.parseInt(pageNum);
        int pageSizeInt = Integer.parseInt(pageSize);
        Map<String, Object> result = attendanceRecordDAO.findRecordsByPageAndKeyword(keyword, pageNumInt, pageSizeInt);
        return new ApiResult(200, "分页模糊查询考勤记录成功", result);
    }

    /**
     * 根据学生ID查询考勤记录，并更新已过期的签到状态
     *
     * @param req       HttpServletRequest
     * @param resp      HttpServletResponse
     * @param studentId 学生ID
     * @return 考勤记录列表
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult findByStudentId(HttpServletRequest req, HttpServletResponse resp, String studentId) throws SQLException {
        int studentIdInt = Integer.parseInt(studentId);

        // 更新已过期的签到状态，只更新 status 为 null 的记录
        String updateExpiredSql = "UPDATE tb_attendance_record AS ar " +
                "JOIN tb_attendance AS a ON ar.attendance_id = a.id " +
                "SET ar.status = '签到过期' " +
                "WHERE ar.student_id = ? AND a.end_time < NOW() AND ar.status IS NULL";
        JDBCUtils.execute(updateExpiredSql, studentIdInt);

        // 查询更新后的考勤记录
        String querySql = "SELECT * FROM tb_attendance_record WHERE student_id = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(querySql, studentIdInt);
        List<AttendanceRecord> records = new ArrayList<>();
        while (rs.next()) {
            AttendanceRecord record = new AttendanceRecord();
            // 设置 AttendanceRecord 对象的属性，并处理空值
            record.setId(rs.getInt("id"));
            record.setAttendanceId(rs.getInt("attendance_id"));
            record.setStudentId(rs.getInt("student_id"));
            record.setRecordType(rs.getString("record_type"));
            record.setCheckInTime(rs.getTimestamp("check_in_time") != null ? rs.getTimestamp("check_in_time").toLocalDateTime() : null);
            record.setStartTime(rs.getTimestamp("start_time") != null ? rs.getTimestamp("start_time").toLocalDateTime() : null);
            record.setEndTime(rs.getTimestamp("end_time") != null ? rs.getTimestamp("end_time").toLocalDateTime() : null);
            record.setReason(rs.getString("reason"));
            record.setStatus(rs.getString("status"));
            record.setCreatedAt(rs.getTimestamp("created_at") != null ? rs.getTimestamp("created_at").toLocalDateTime() : null);
            record.setRecordImage(rs.getString("record_image"));
            records.add(record);
        }

        return new ApiResult(200, "根据学生ID查询考勤记录成功", records);
    }

    /**
     * 根据考勤ID查询考勤记录
     *
     * @param req          HttpServletRequest
     * @param resp         HttpServletResponse
     * @param attendanceId 考勤ID
     * @return 考勤记录列表
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult findByAttendanceId(HttpServletRequest req, HttpServletResponse resp, String attendanceId) throws SQLException {
        int attendanceIdInt = Integer.parseInt(attendanceId);
        List<AttendanceRecord> records = attendanceRecordDAO.findByAttendanceId(attendanceIdInt);
        return new ApiResult(200, "根据考勤ID查询考勤记录成功", records);
    }

    /**
     * 根据记录类型查询考勤记录
     *
     * @param req         HttpServletRequest
     * @param resp        HttpServletResponse
     * @param recordType  记录类型
     * @return 考勤记录列表
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult findByRecordType(HttpServletRequest req, HttpServletResponse resp, String recordType) throws SQLException {
        List<AttendanceRecord> records = attendanceRecordDAO.findByRecordType(recordType);
        return new ApiResult(200, "根据记录类型查询考勤记录成功", records);
    }

    /**
     * 根据状态查询考勤记录
     *
     * @param req    HttpServletRequest
     * @param resp   HttpServletResponse
     * @param status 记录状态
     * @return 考勤记录列表
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult findByStatus(HttpServletRequest req, HttpServletResponse resp, String status) throws SQLException {
        List<AttendanceRecord> records = attendanceRecordDAO.findByStatus(status);
        return new ApiResult(200, "根据状态查询考勤记录成功", records);
    }

    /**
     * 根据时间段查询考勤记录
     *
     * @param req        HttpServletRequest
     * @param resp       HttpServletResponse
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @return 考勤记录列表
     * @throws SQLException 数据库异常
     */
    @ResponseBody
    public ApiResult findByTimeRange(HttpServletRequest req, HttpServletResponse resp, LocalDateTime startTime, LocalDateTime endTime) throws SQLException {
        List<AttendanceRecord> records = attendanceRecordDAO.findByTimeRange(startTime, endTime);
        return new ApiResult(200, "根据时间段查询考勤记录成功", records);
    }
}